//
// Created by shenbin on 2022/4/24.
// https://leetcode-cn.com/problems/subdomain-visit-count/
//

#ifndef ALGORITHM_TRAINNING_W02_H01_LC811_H
#define ALGORITHM_TRAINNING_W02_H01_LC811_H

#include <string>
#include <vector>
#include <unordered_map>


using namespace std;

class LeetCode811 {
public:
    vector<string> subdomainVisits(vector<string> &cpdomains) {
        for (string domain: cpdomains) {
            // 找到“ ”所在的位置；
            string::size_type nPos = domain.find(" ", 0);
            // 提取visit count，转换为整型
            int visitCount = atoi(domain.substr(0, nPos).c_str());
            do {
                //从" "后取出域名；
                string subDomain = domain.substr(nPos + 1);
                //在hash表中查找，如果找到，就累加
                if (h.find(subDomain) != h.end()) {
                    h[subDomain] += visitCount;
                } else {
                    h[subDomain] = visitCount;
                }
                //找下一个"."
                nPos = domain.find(".", nPos + 1);

            } while (nPos != string::npos);// 没找到nPos != string::npos，而不是-1
        }
        vector<string> ans;
        for (const pair<string, long long> &domain: h) {

            ans.push_back(to_string(domain.second) + " " + domain.first);
        }
        return ans;
    }

private:
    unordered_map<string, int> h;
};

#endif //ALGORITHM_TRAINNING_W02_H01_LC811_H
